import logging
import sys
from typing import Generator, Any

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

from configs.basic_config import ORACLE_LIB_DIR, ORACLE_USER, ORACLE_PASSWORD, ORACLE_HOST, ORACLE_PORT, \
    ORACLE_SERVICE_NAME

# 初始化日志
logger = logging.getLogger(__name__)

# 全局变量
oracle_engine = None
OracleSessionLocal = None
Base = declarative_base()

def init_oracle_db():
    """初始化Oracle数据库连接"""
    global oracle_engine, OracleSessionLocal
    
    try:
        import oracledb
        # 根据你提供的初始化语句来初始化Oracle客户端
        # oracledb.init_oracle_client(lib_dir=ORACLE_LIB_DIR)
        try:
            if sys.platform.startswith('win'):
                logger.info("env: windows ==>> loading big_data_center_oracle_engine")
                oracledb.init_oracle_client(lib_dir=ORACLE_LIB_DIR)
            else:
                logger.info("env: Linux ==>> loading big_data_center_oracle_engine")
                oracledb.init_oracle_client(lib_dir=r'/oracle/instantclient_12_1')
        except Exception as e:
            print(f"big-data-center Oracle ==>> Oracle Client 初始化失败: {e}")
            raise
        
        # 创建Oracle数据库连接URL
        ORACLE_DATABASE_URL = f"oracle+oracledb://{ORACLE_USER}:{ORACLE_PASSWORD}@{ORACLE_HOST}:{ORACLE_PORT}/{ORACLE_SERVICE_NAME}"

        # 创建引擎
        oracle_engine = create_engine(
            ORACLE_DATABASE_URL,
            pool_pre_ping=True,
            pool_recycle=3600,
            echo=False
        )

        OracleSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=oracle_engine)
        logger.info("Oracle数据库连接初始化成功")
        return OracleSessionLocal
    except ImportError as e:
        logger.warning(f"Oracle数据库模块导入失败: {e}")
        return None
    except Exception as e:
        logger.warning(f"Oracle数据库连接初始化失败: {e}")
        return None

def get_oracle_db() -> Generator[Any, Any, Any]:
    """获取Oracle数据库会话"""
    # 只在引擎未初始化时才初始化
    if oracle_engine is None or OracleSessionLocal is None:
        init_oracle_db()
    
    if oracle_engine is None or OracleSessionLocal is None:
        raise Exception("Oracle数据库未初始化或不可用")
    db = OracleSessionLocal()
    try:
        yield db
    finally:
        db.close()